package com.jdd.modules.parkCarAbnormalRecord.service.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jdd.common.constant.CacheConstant;
import com.jdd.common.constant.JddConstant;
import com.jdd.common.system.vo.LoginUser;
import com.jdd.common.util.CacheUtil;
import com.jdd.common.util.SnowFlakeUtil;
import com.jdd.modules.parkCarAbnormalRecord.entity.ParkCarAbnormalRecord;
import com.jdd.modules.parkCarAbnormalRecord.enums.AbnormalTypeEnums;
import com.jdd.modules.parkCarAbnormalRecord.mapper.ParkCarAbnormalRecordMapper;
import com.jdd.modules.parkCarAbnormalRecord.service.IParkCarAbnormalRecordService;
import com.jdd.modules.parkCarAbnormalRecord.vo.ParkCarAbnormalRecordVO;
import com.jdd.modules.parkCarAbnormalRecord.vo.QueryCarDetailsListDTO;
import com.jdd.modules.parking.entity.ParkArmInfo;
import com.jdd.modules.parking.mapper.ParkCarEnterLogMapper;
import com.jdd.modules.parking.entity.ParkCarEnterLog;
import com.jdd.modules.parking.service.IParkWorkStationService;
import com.jdd.modules.parking.service.IparkCarEnterLogService;
import com.jdd.modules.sdk.SdkCallInterface;
import com.jdd.modules.sdkidentifyresultpushlog.entity.SdkIdentifyResultPushLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Description: 车场异常记录
 * @Author: jdd
 * @Date: 2022-04-21
 * @Version: V1.0
 */
@Service
@Slf4j
public class ParkCarAbnormalRecordServiceImpl extends ServiceImpl<ParkCarAbnormalRecordMapper, ParkCarAbnormalRecord>
        implements IParkCarAbnormalRecordService {

    @Resource
    private SdkCallInterface sdkCallInterface;

    @Resource
    private IParkWorkStationService parkWorkStationService;

    @Resource
    private ParkCarAbnormalRecordMapper parkCarAbnormalRecordMapper;

    @Resource
    private IparkCarEnterLogService parkCarEnterLogService;

    @Resource
    private ParkCarEnterLogMapper parkCarEnterLogMapper;

    @Resource
    private CacheUtil cacheUtil;

    @Override
    public Boolean abnormalRecordForceTrigger(String serialNo) {
        //触发一次抓拍操作
        try {
            cacheUtil.put(CacheConstant.EMERGENCY_OPENING_SERIALNO_NAME, CacheConstant.EMERGENCY_OPENING_SERIALNO_KEY, serialNo);
            //软出发回调函数内处理异常记录的逻辑
            sdkCallInterface.TriggerExtAll(serialNo);
        } catch (Exception e) {
            log.error("应急开闸，保存异常记录时错误：{}", e.getMessage());
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Boolean saveAbnormalRecord(SdkIdentifyResultPushLog sdkIdentifyResultPushLog,
                                      ParkArmInfo parkArmInfo,
                                      AbnormalTypeEnums abnormalTypeEnums) {
        String plateNo = null;
        String ossImg = null;
        String img = null;
        String armName = null;
        ParkCarEnterLog lastCarEnterLog = null;
        Map<String, String> map = getCarInfo(parkArmInfo.getSerialNo());
        if (MapUtil.isNotEmpty(map)) {
            plateNo = map.get("plateNo");
            ossImg = map.get("ossImg");
            img = map.get("img");
            armName = map.get("armName");
        }
        //根据识别的车牌号获取其最近的一条入场纪录的批次号
        //根据识别的车牌号获取其最近的一条入场纪录的批次号
        if (StringUtils.isNotBlank(plateNo)){
            lastCarEnterLog = parkCarEnterLogService.getLastCarEnterLog(parkArmInfo.getParkCode(),
                    plateNo, JddConstant.ParkCarEnterLog.CAR_NO_OUT);
        }

        ParkCarAbnormalRecord parkCarAbnormalRecord = new ParkCarAbnormalRecord();
        parkCarAbnormalRecord.setId(SnowFlakeUtil.getId());
        parkCarAbnormalRecord.setParkCode(parkArmInfo.getParkCode());
        parkCarAbnormalRecord.setParkName(parkArmInfo.getParkName());
        if (Objects.nonNull(lastCarEnterLog)) {
            parkCarAbnormalRecord.setEnterBatchNumber(lastCarEnterLog.getBatchNumber());
        }
        parkCarAbnormalRecord.setPlateNo(plateNo);
        parkCarAbnormalRecord.setIdentifyPlateNo(sdkIdentifyResultPushLog.getLicense());
        parkCarAbnormalRecord.setSerialNo(parkArmInfo.getSerialNo());
        parkCarAbnormalRecord.setArmName(parkArmInfo.getArmName());
        parkCarAbnormalRecord.setIdentifyImgPath(img);
        parkCarAbnormalRecord.setImgPath(sdkIdentifyResultPushLog.getImg());
        Date nowDate = new Date();
        parkCarAbnormalRecord.setTriggerTime(nowDate);
        parkCarAbnormalRecord.setAbnormalType(abnormalTypeEnums.getCode());
        parkCarAbnormalRecord.setCreateTime(nowDate);
        parkCarAbnormalRecord.setDeleted(0);
        //加上工作站名和岗亭人账户
        String workUser = parkWorkStationService.getStationOperationNameByParkArm(parkArmInfo);
        if (ObjectUtils.isNotEmpty(workUser)) {
            parkCarAbnormalRecord.setWorkStationName(parkArmInfo.getWorkStationName());
            parkCarAbnormalRecord.setWorkStationOperator(workUser);
        }
        save(parkCarAbnormalRecord);
        return true;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED ,rollbackFor = Exception.class)
    public void saveRemoteControlAbnormalRecord(SdkIdentifyResultPushLog sdkIdentifyResultPushLog, ParkArmInfo parkArmInfo, AbnormalTypeEnums emergencyOpening) {
        String plateNo = null;
        String ossImg = null;
        String img = null;
        String armName = null;
        ParkCarEnterLog lastCarEnterLog =null;
        Map<String, String> map = getCarInfo(parkArmInfo.getSerialNo());
        if (MapUtil.isNotEmpty(map)) {
            plateNo = map.get("plateNo");
            ossImg = map.get("ossImg");
            img = map.get("img");
            armName = map.get("armName");
        }
        //根据识别的车牌号获取其最近的一条入场纪录的批次号
        if (StringUtils.isNotBlank(plateNo)){
              lastCarEnterLog = parkCarEnterLogService.getLastCarEnterLog(parkArmInfo.getParkCode(),
                    plateNo, JddConstant.ParkCarEnterLog.CAR_NO_OUT);
        }

        ParkCarAbnormalRecord parkCarAbnormalRecord = new ParkCarAbnormalRecord();
        parkCarAbnormalRecord.setId(SnowFlakeUtil.getId());
        parkCarAbnormalRecord.setParkCode(parkArmInfo.getParkCode());
        parkCarAbnormalRecord.setParkName(parkArmInfo.getParkName());
        if (Objects.nonNull(lastCarEnterLog)){
            parkCarAbnormalRecord.setEnterBatchNumber(lastCarEnterLog.getBatchNumber());
        }
        parkCarAbnormalRecord.setPlateNo(plateNo);
        parkCarAbnormalRecord.setIdentifyPlateNo(sdkIdentifyResultPushLog.getLicense());
        parkCarAbnormalRecord.setSerialNo(parkArmInfo.getSerialNo());
        parkCarAbnormalRecord.setArmName(parkArmInfo.getArmName());
        parkCarAbnormalRecord.setIdentifyImgPath(img);
        parkCarAbnormalRecord.setImgPath(sdkIdentifyResultPushLog.getImg());
        Date nowDate = new Date();
        parkCarAbnormalRecord.setTriggerTime(nowDate);
        parkCarAbnormalRecord.setAbnormalType(emergencyOpening.getCode());
        parkCarAbnormalRecord.setCreateTime(nowDate);
        parkCarAbnormalRecord.setDeleted(0);
        //加上工作站名和岗亭人账户
        String workUser = parkWorkStationService.getStationOperationNameByParkArm(parkArmInfo);
        if (ObjectUtils.isNotEmpty(workUser)) {
            parkCarAbnormalRecord.setWorkStationName(parkArmInfo.getWorkStationName());
            parkCarAbnormalRecord.setWorkStationOperator(workUser);
        }
        save(parkCarAbnormalRecord);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletedLastestAbnormalRecord(String parkCode, String plateNo, String serialNo) {
        parkCarAbnormalRecordMapper.deletedLastestAbnormalRecord(parkCode,plateNo,serialNo);
    }

    @Override
    public IPage<ParkCarAbnormalRecordVO> queryCarDetailsList(Page<ParkCarAbnormalRecordVO> page, QueryCarDetailsListDTO queryCarDetailsListDTO) {

        IPage<ParkCarAbnormalRecordVO> parkCarAbnormalRecordDetails= parkCarEnterLogMapper.queryCarDetailsList(page,queryCarDetailsListDTO.getBatchNumber(),queryCarDetailsListDTO.getSerialNo());

        return parkCarAbnormalRecordDetails;
    }


    public Map<String, String> getCarInfo(String serialNo) {
        log.info("-----------------------" + serialNo);
        Map<String, String> map = new HashMap<>(16);
        String carInfo = cacheUtil.get(CacheConstant.CURRENT_EXIT_LICENSE_PLATE, serialNo);
        log.info("cache缓存内容>carInfo:{}", carInfo);
        if (StringUtils.isNotBlank(carInfo) && !"null".equalsIgnoreCase(carInfo)) {
            log.info("carInfo：" + carInfo);
            String[] carInfoArray = carInfo.split("#");
            if (ArrayUtils.isNotEmpty(carInfoArray) && carInfoArray.length >= 2) {
                map.put("plateNo", carInfoArray[0]);
                map.put("ossImg", carInfoArray[1]);
                map.put("img", carInfoArray[2]);
                map.put("armName", carInfoArray[3]);
            }
        }
        return map;
    }
}
